package com.kit;

import java.io.File;
import java.util.HashMap;
import java.util.Map;

import org.apache.commons.codec.binary.Base64;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.jplus.core.utill.HttpClientUtil;
import com.jplus.core.utill.StreamUtil;

public class OcrKit {

	public static void main(String[] args) {
		String path = "D:/OCR/";
		String file = path + "/IMG_1032.JPG";
		ImgCutKit.doCut(path, 500);
		System.out.println(doOcrBD(new File(file)));
	}

	public static JSONObject doOcrBD(File file) {
		HttpClientUtil http = new HttpClientUtil();
		String acckey = "yQuZ2pdMApVqgAQfULgOdUYl";
		String seckey = "UZMfWol2ci5LYPFEpUlznXTFGB0mf8XM";
		http.setHeader("Content-Type", "application/x-www-form-urlencoded");
		String urlToken = "https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id=" + acckey + "&client_secret=" + seckey;
		String tokenRes = http.doGet(urlToken);
		System.err.println(tokenRes);
		JSONObject tokenObj = JSON.parseObject(tokenRes);// 有效期一般为1个月
		String access_token = tokenObj.getString("access_token");
		String urlOrc = "https://aip.baidubce.com/rest/2.0/ocr/v1/general_basic?access_token=" + access_token;
		Map<String, Object> obj = new HashMap<>();
		obj.put("image", encodeBase64(StreamUtil.toReadFile(file)));
		obj.put("url", "");// 和image二选一
		obj.put("language_type", "CHN_ENG");// 中英文混合；
		obj.put("detect_direction", "true");// 检测朝向
		obj.put("detect_language", "false");// 检测语言
		obj.put("probability", "false");// 返回置信度
		JSONObject res = JSON.parseObject(http.doPost(urlOrc, obj));
		return res;
	}

	public static String encodeBase64(byte[] b) {
		Base64 base64 = new Base64();
		b = base64.encode(b);
		String s = new String(b);
		return s;
	}
}
